package com.cc.moxingvoice.lock;

import android.app.Dialog;
import android.content.Context;
import android.databinding.BaseObservable;
import android.databinding.ViewDataBinding;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;

import com.cc.moxingvoice.BR;
import com.cc.moxingvoice.R;
import com.cc.moxingvoice.base.BaseLock;
import com.cc.moxingvoice.constant.LocalPath;
import com.cc.moxingvoice.databinding.ActivityAddVoiceBinding;
import com.cc.moxingvoice.model.AddVoiceItem;
import com.cc.moxingvoice.ui.voice.AddVoiceAdapter;
import com.cc.moxingvoice.utils.FilesUtil;
import com.cc.moxingvoice.utils.PinyinComparator;
import com.cc.moxingvoice.utils.RegexUtil;
import com.cc.moxingvoice.widget.dialog.ButtonTwoDialog;
import com.mob.analysdk.AnalySDK;
import com.superc.cframework.base.ui.CBaseRecyclerViewAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * 创建日期：2018/3/4 on 22:06
 * 描述：
 * 作者：郭士超
 * QQ：1169380200
 */

public class AddVoiceLock extends BaseLock<ActivityAddVoiceBinding> {

    public static final int LOCAL = 1;
    public static final int MO = 2;
    public static final int QQ = 3;
    public static final int QQD = 4;
    public static final int WX = 5;

    private int type;

    private List<AddVoiceItem> mList;
    private AddVoiceAdapter mAdapter;

    private List<AddVoiceItem> mAllList;

    private BindingData mBindingData;

    private String title;

    private List<String> mPathList;
    private String qqVoicePath;

    public AddVoiceLock(Context context, ActivityAddVoiceBinding binding) {
        super(context, binding);
    }

    public AddVoiceLock(Context context, ActivityAddVoiceBinding binding, Bundle bundle) {
        super(context, binding, bundle);
    }

    @Override
    protected void init() {
        title = mBundle.getString("title");
        mBindingData = new BindingData("", "");
        initList();
        initData();
        initPathList();
        initListener();

        type = mBundle.getInt("type");
        switch (type) {
            case LOCAL:
                mPathList.add(LocalPath.SD_PATH);
                addLocalList();
                break;
            case MO:
                mPathList.add(LocalPath.VOICE_PATH);
                addMoList();
                break;
            case QQD:
                addQQDList();
                break;
            case QQ:
                addQQList();
                break;
            case WX:
                addWXList();
                break;
        }
    }

    private void initData() {
        Calendar c = Calendar.getInstance(); // 当前时间
        int year = c.get(Calendar.YEAR); // 获取当前年份
        int month = c.get(Calendar.MONTH) + 1;// 获取当前月份
        int day = c.get(Calendar.DAY_OF_MONTH);// 获取当日期

        String yearMonth = "" + year + (month >= 10 ? "" + month : "0" + month);
        qqVoicePath = "/" + "ptt/"; //  + yearMonth + "/" + day + "/"
    }

    private void initListener() {
        mBinding.edtFile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //在这里写一些东西，这里面是每当text改变的时候就会触发
                searchList();
            }
        });
    }

    private void searchList() {
        if (mBindingData.edit.isEmpty()) {
            mList.clear();
            mList.addAll(mAllList);
            mAdapter.notifyDataSetChanged();
            return;
        }

        mList.clear();

        for (AddVoiceItem item : mAllList) {
            if (item.getName().length() >= mBindingData.edit.length()
                    && item.getName().toLowerCase().contains(mBindingData.edit.toLowerCase())) {
                mList.add(item);
            }
        }

        mAdapter.notifyDataSetChanged();
    }

    private void addQQDList() {
        mAllList.clear();

        String nowPath = LocalPath.QQ_DOWNLOAD_PATH;
        mBindingData.path = nowPath;
        mBindingData.notifyChange();

        List<String> voiceList = FilesUtil.getVoiceFileName(nowPath);
        Drawable VoicePic = getContext().getResources().getDrawable(R.drawable.voice);
        for (String voice : voiceList) {
            mAllList.add(new AddVoiceItem(voice, nowPath + voice, VoicePic, true));
        }

        mList.clear();
        mList.addAll(mAllList);
        mAdapter.notifyDataSetChanged();
    }

    private void addQQList() {
        mAllList.clear();

        String nowPath = "QQ收发所有语音";
        mBindingData.path = nowPath;
        mBindingData.notifyChange();

        String voicePath = LocalPath.QQ_VOICE_PATH;
        List<String> labelList = FilesUtil.getFolderName(voicePath);
        Drawable VoicePic = getContext().getResources().getDrawable(R.drawable.voice);
        for (String label : labelList) {
            String voiceLabelPath = voicePath + label + qqVoicePath;
            if (!RegexUtil.isQQNumber(label) || !FilesUtil.isFileExists(voiceLabelPath)) {
                continue;
            }
            List<String> voiceList = FilesUtil.getVoiceFileName(voiceLabelPath);
            if (voiceList.size() > 0) {
                for (String voice : voiceList) {
                    mAllList.add(new AddVoiceItem(voice,voiceLabelPath + voice, VoicePic, true));
                }
            }
        }
        Collections.sort(mAllList);  // 对象数组排序
        while (mAllList.size() > LocalPath.VOICE_NUM){
            FilesUtil.delete(mAllList.get(LocalPath.VOICE_NUM).getPath());
            mAllList.remove(LocalPath.VOICE_NUM);
        }

        mList.clear();
        mList.addAll(mAllList);
        mAdapter.notifyDataSetChanged();
    }

    private void addWXList() {
        mAllList.clear();

        String nowPath = "微信收发所有语音";
        mBindingData.path = nowPath;
        mBindingData.notifyChange();

        String voicePath = LocalPath.WX_VOICE_PATH;
        List<String> labelList = FilesUtil.getFolderName(voicePath);
        Drawable VoicePic = getContext().getResources().getDrawable(R.drawable.voice);
        for (String label : labelList) {
            String voiceLabelPath = voicePath + label + "/" + "voice2/";
            if (label.length() < 25 || !FilesUtil.isFileExists(voiceLabelPath)) {
                continue;
            }
            List<String> voicePathList = FilesUtil.getAllVoiceFileName(voiceLabelPath);
            if (voicePathList.size() > 0) {
                for (String path : voicePathList) {
                    mAllList.add(new AddVoiceItem(FilesUtil.getFileNameHandExtension(path), path, VoicePic, true));
                }
            }
        }
        Collections.sort(mAllList);  // 对象数组排序
        while (mAllList.size() > LocalPath.VOICE_NUM){
            FilesUtil.delete(mAllList.get(LocalPath.VOICE_NUM).getPath());
            mAllList.remove(LocalPath.VOICE_NUM);
        }

        mList.clear();
        mList.addAll(mAllList);
        mAdapter.notifyDataSetChanged();
    }

    private void addMoList() {
        mAllList.clear();

        if (mPathList.size() > 1) {
            Drawable pic = getContext().getResources().getDrawable(R.drawable.folder);
            mAllList.add(new AddVoiceItem(mContext.getString(R.string.go_back), "", pic, false));
        }

        String nowPath = mPathList.get(mPathList.size() - 1);
        if (mPathList.get(0) != null) {
            mBindingData.path = nowPath.substring(mPathList.get(0).length(), nowPath.length());
            mBindingData.notifyChange();
        }
        List<String> folderList = FilesUtil.getFolderName(nowPath);
        if (folderList.size() <= 50) {
            Collections.sort(folderList, new PinyinComparator());
        }
        Drawable folderPic = getContext().getResources().getDrawable(R.drawable.folder);
        for (String folder : folderList) {
            mAllList.add(new AddVoiceItem(folder, mPathList.get(mPathList.size() - 1) + folder, folderPic, false));
        }
        List<String> voiceList = FilesUtil.getVoiceFileName(nowPath);
        if (voiceList.size() <= 50) {
            Collections.sort(voiceList, new PinyinComparator());
        }
        Drawable VoicePic = getContext().getResources().getDrawable(R.drawable.voice);
        for (String voice : voiceList) {
            mAllList.add(new AddVoiceItem(voice, mPathList.get(mPathList.size() - 1) + voice, VoicePic, true));
        }

        mList.clear();
        mList.addAll(mAllList);
        mAdapter.notifyDataSetChanged();
    }

    private void addLocalList() {
        mAllList.clear();

        if (mPathList.size() > 1) {
            Drawable pic = getContext().getResources().getDrawable(R.drawable.folder);
            mAllList.add(new AddVoiceItem(mContext.getString(R.string.go_back), "", pic, false));
        }

        String nowPath = mPathList.get(mPathList.size() - 1);
        mBindingData.path = nowPath;
        mBindingData.notifyChange();
        List<String> folderList = FilesUtil.getFolderName(nowPath);
        if (folderList.size() <= 50) {
            Collections.sort(folderList, new PinyinComparator());
        }
        Drawable folderPic = getContext().getResources().getDrawable(R.drawable.folder);
        for (String folder : folderList) {
            mAllList.add(new AddVoiceItem(folder, mPathList.get(mPathList.size() - 1) + folder, folderPic, false));
        }
        List<String> voiceList = FilesUtil.getVoiceFileName(nowPath);
        if (voiceList.size() <= 50) {
            Collections.sort(voiceList, new PinyinComparator());
        }
        Drawable VoicePic = getContext().getResources().getDrawable(R.drawable.voice);
        for (String voice : voiceList) {
            mAllList.add(new AddVoiceItem(voice, mPathList.get(mPathList.size() - 1) + voice, VoicePic, true));
        }

        mList.clear();
        mList.addAll(mAllList);
        mAdapter.notifyDataSetChanged();
    }

    private void initPathList() {
        mPathList = new ArrayList<String>();
    }

    private void initList() {
        mAllList = new ArrayList<AddVoiceItem>();

        mList = new ArrayList<AddVoiceItem>();
        LinearLayoutManager ms = new LinearLayoutManager(mContext);
        mBinding.rvFiles.setLayoutManager(ms);
        mAdapter = new AddVoiceAdapter(mContext, mList, R.layout.item_add_voice, BR.item);
        mBinding.rvFiles.setAdapter(mAdapter); // 这里或者在xml里设置adapter
        mAdapter.setOnItemClickListener(new CBaseRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ViewDataBinding binding, int position) {
                if (type == QQ || type == QQD || type == WX) {
                    // 添加
                    showAddDialog(position);
                    return;
                }

                if (mPathList.size() > 1 && position == 0) {
                    mPathList.remove(mPathList.size() - 1);
                    mBindingData.edit = "";
                    mBindingData.notifyChange();
                    addTypeList();
                    return;
                }

                if (mList.get(position).isVoice()) {
                    // 添加
                    showAddDialog(position);
                } else {
                    mPathList.add(mPathList.get(mPathList.size() - 1) + mList.get(position).getName() + "/");
                    mBindingData.edit = "";
                    mBindingData.notifyChange();
                    addTypeList();
                }
            }
        });
    }

    private void addTypeList() {
        switch (type) {
            case LOCAL:
                addLocalList();
                break;
            case MO:
                addMoList();
                break;
        }
    }

    private void showAddDialog(final int position) {
        new ButtonTwoDialog(mContext, R.style.dialog, mContext.getString(R.string.sure_add_voice), new ButtonTwoDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    String oldPath = mList.get(position).getPath();
                    String newPath = LocalPath.VOICE_PATH + title + "/" + mList.get(position).getName();
                    // 循环判断直到生成可用的副本名
                    while (FilesUtil.isFileExists(newPath)) {
                        //重命名重名定义规范--Util.getCopyNameFromOriginal(String)-自定义方法：根据自定义规则生成原名称副本
                        newPath = FilesUtil.getCopyNameFromOriginal(newPath);
                    }
                    if (FilesUtil.isFileExists(oldPath)) {
                        FilesUtil.copyFile(oldPath, newPath);
                        showToast("添加成功");
                    } else {
                        showToast("添加失败");
                    }

                    HashMap<String, Object> eventParams = new HashMap<String, Object>();
                    eventParams.put("voice-package", title);
                    AnalySDK.trackEvent("add-voice", eventParams);

                    dialog.dismiss();
                }
            }
        }).setTitle(mContext.getString(R.string.hint)).show();
    }

    public BindingData getBindingData() {
        return mBindingData;
    }

    public void setBindingData(BindingData bindingData) {
        mBindingData = bindingData;
    }

    public class BindingData extends BaseObservable {

        private String path;
        private String edit;

        public BindingData(String path, String edit) {
            this.path = path;
            this.edit = edit;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String url) {
            this.path = url;
        }

        public String getEdit() {
            return edit;
        }

        public void setEdit(String edit) {
            this.edit = edit;
        }
    }

}
